<template>
  <div class="proxy-management">
    <el-card class="proxy-card">
      <template #header>
        <div class="card-header">
          <span>代理管理</span>
          <div class="header-actions">
            <el-button
              type="danger"
              :disabled="!selectedRows.length"
              @click="handleBatchDelete"
            >
              删除选中
            </el-button>
            <el-button
              type="success"
              :disabled="!selectedRows.length"
              @click="handleBatchTest"
            >
              测试选中
            </el-button>
            <el-button type="primary" @click="handleAdd">添加代理</el-button>
          </div>
        </div>
      </template>

      <el-table 
        :data="proxyList" 
        style="width: 100%" 
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="protocol" label="协议" width="100">
          <template #default="{ row }">
            <el-tag :type="getProtocolTagType(row.protocol)">
              {{ row.protocol }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="ip" label="IP地址" />
        <el-table-column prop="port" label="端口号" width="100" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="password" label="密码" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ hidePassword(row.password) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
              {{ row.status === 'active' ? '可用' : '不可用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button-group>
              <el-button size="small" type="primary" @click="handleEdit(row)">
                编辑
              </el-button>
              <el-button size="small" type="success" @click="handleTest(row)">
                测试
              </el-button>
              <el-button size="small" type="danger" @click="handleDelete(row)">
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑代理对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加代理' : '编辑代理'"
      width="500px"
    >
      <el-form
        ref="proxyFormRef"
        :model="proxyForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="协议" prop="protocol">
          <el-select v-model="proxyForm.protocol" placeholder="请选择协议">
            <el-option label="HTTP" value="http" />
            <el-option label="HTTPS" value="https" />
            <el-option label="SOCKS5" value="socks5" />
          </el-select>
        </el-form-item>
        <el-form-item label="IP地址" prop="ip">
          <el-input v-model="proxyForm.ip" placeholder="请输入IP地址" />
        </el-form-item>
        <el-form-item label="端口号" prop="port">
          <el-input-number
            v-model="proxyForm.port"
            :min="1"
            :max="65535"
            placeholder="请输入端口号"
          />
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="proxyForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="proxyForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const loading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref('add')
const proxyFormRef = ref(null)
const selectedRows = ref([])

// 表单校验规则
const rules = {
  protocol: [{ required: true, message: '请选择协议', trigger: 'change' }],
  ip: [{ required: true, message: '请输入IP地址', trigger: 'blur' }],
  port: [{ required: true, message: '请输入端口号', trigger: 'blur' }],
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

// 代理表单
const proxyForm = reactive({
  protocol: '',
  ip: '',
  port: null,
  username: '',
  password: ''
})

// 模拟数据
const proxyList = ref([
  {
    id: 1,
    protocol: 'http',
    ip: '192.168.1.100',
    port: 8080,
    username: 'user1',
    password: '******',
    status: 'active'
  },
  {
    id: 2,
    protocol: 'socks5',
    ip: '192.168.1.101',
    port: 1080,
    username: 'user2',
    password: '******',
    status: 'inactive'
  }
])

// 获取协议标签类型
const getProtocolTagType = (protocol) => {
  const types = {
    http: '',
    https: 'success',
    socks5: 'warning'
  }
  return types[protocol] || 'info'
}

// 隐藏密码
const hidePassword = (password) => '*'.repeat(6)

// 处理多选变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 批量删除
const handleBatchDelete = () => {
  if (!selectedRows.value.length) return
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRows.value.length} 个代理吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    const selectedIds = selectedRows.value.map(row => row.id)
    proxyList.value = proxyList.value.filter(item => !selectedIds.includes(item.id))
    selectedRows.value = []
    ElMessage.success('批量删除成功')
  })
}

// 批量测试
const handleBatchTest = async () => {
  if (!selectedRows.value.length) return

  try {
    loading.value = true
    // 模拟测试过程
    await Promise.all(selectedRows.value.map(async (proxy) => {
      await new Promise(resolve => setTimeout(resolve, 1000))
      return proxy
    }))
    ElMessage.success(`已完成 ${selectedRows.value.length} 个代理的测试`)
  } catch (error) {
    ElMessage.error('部分代理测试失败')
  } finally {
    loading.value = false
  }
}

// 添加代理
const handleAdd = () => {
  dialogType.value = 'add'
  Object.keys(proxyForm).forEach(key => proxyForm[key] = '')
  dialogVisible.value = true
}

// 编辑代理
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(proxyForm, row)
  dialogVisible.value = true
}

// 测试代理
const handleTest = async (row) => {
  try {
    loading.value = true
    // 模拟测试过程
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('代理测试成功')
  } catch (error) {
    ElMessage.error('代理测试失败')
  } finally {
    loading.value = false
  }
}

// 删除代理
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除这个代理吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    proxyList.value = proxyList.value.filter(item => item.id !== row.id)
    ElMessage.success('删除成功')
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!proxyFormRef.value) return
  
  await proxyFormRef.value.validate((valid) => {
    if (valid) {
      if (dialogType.value === 'add') {
        // 添加新代理
        const newProxy = {
          id: Date.now(),
          ...proxyForm,
          status: 'active'
        }
        proxyList.value.push(newProxy)
        ElMessage.success('添加成功')
      } else {
        // 更新现有代理
        const index = proxyList.value.findIndex(item => item.id === proxyForm.id)
        if (index !== -1) {
          proxyList.value[index] = { ...proxyList.value[index], ...proxyForm }
          ElMessage.success('更新成功')
        }
      }
      dialogVisible.value = false
    }
  })
}
</script>

<style scoped>
.proxy-management {
  padding: 20px;
}

.proxy-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

:deep(.el-button-group) {
  .el-button {
    padding: 5px 12px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
